package com.example.pclimb.ui.auth;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.MainActivity;
import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityLoginBinding;
import com.example.pclimb.databinding.DialogAdminLoginBinding;
import com.example.pclimb.model.User;
import com.example.pclimb.ui.admin.AdminPanelActivity;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.UserViewModel;
import com.google.android.material.textfield.TextInputEditText;

/**
 * 登录页面
 */
public class LoginActivity extends AppCompatActivity {

    private ActivityLoginBinding binding;
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        // 检查是否已登录
        if (SharedPreferencesUtil.getUserId(this) > 0) {
            startMainActivity();
            return;
        }
        
        // 初始化ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        
        // 设置登录按钮点击事件
        binding.btnLogin.setOnClickListener(v -> attemptLogin());
        
        // 设置注册提示点击事件
        binding.tvRegisterPrompt.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
        
        // 添加管理员登录入口
        binding.tvAdminLogin.setOnClickListener(v -> showAdminLoginDialog());
    }
    
    /**
     * 尝试登录
     */
    private void attemptLogin() {
        // 重置错误提示
        binding.tilUsername.setError(null);
        binding.tilPassword.setError(null);
        
        // 获取输入值
        String username = binding.etUsername.getText().toString().trim();
        String password = binding.etPassword.getText().toString().trim();
        
        // 验证输入
        boolean cancel = false;
        View focusView = null;
        
        if (TextUtils.isEmpty(password)) {
            binding.tilPassword.setError(getString(R.string.error_field_required));
            focusView = binding.etPassword;
            cancel = true;
        }
        
        if (TextUtils.isEmpty(username)) {
            binding.tilUsername.setError(getString(R.string.error_field_required));
            focusView = binding.etUsername;
            cancel = true;
        }
        
        if (cancel) {
            // 输入有误，聚焦到错误输入框
            focusView.requestFocus();
        } else {
            // 显示进度条，执行登录
            showProgress(true);
            userViewModel.login(username, password).observe(this, user -> {
                showProgress(false);
                if (user != null) {
                    // 登录成功，保存用户ID
                    SharedPreferencesUtil.saveUserId(LoginActivity.this, user.getId());
                    
                    // 如果用户有token，保存token
                    if (user.getToken() != null && !user.getToken().isEmpty()) {
                        SharedPreferencesUtil.saveAuthToken(LoginActivity.this, user.getToken());
                    }
                    
                    Toast.makeText(LoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                    startMainActivity();
                } else {
                    // 登录失败
                    Toast.makeText(LoginActivity.this, R.string.login_failure, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
    /**
     * 显示或隐藏进度条
     */
    private void showProgress(boolean show) {
        binding.progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.btnLogin.setEnabled(!show);
        binding.etUsername.setEnabled(!show);
        binding.etPassword.setEnabled(!show);
    }
    
    /**
     * 启动主页面
     */
    private void startMainActivity() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    /**
     * 显示管理员登录对话框
     */
    private void showAdminLoginDialog() {
        // 创建对话框布局
        View view = getLayoutInflater().inflate(R.layout.dialog_admin_login, null);
        TextInputEditText etAdminUsername = view.findViewById(R.id.et_admin_username);
        TextInputEditText etAdminPassword = view.findViewById(R.id.et_admin_password);
        
        // 创建并显示对话框
        new AlertDialog.Builder(this)
                .setTitle(R.string.admin_login)
                .setView(view)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    String username = etAdminUsername.getText().toString().trim();
                    String password = etAdminPassword.getText().toString().trim();
                    loginAsAdmin(username, password);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }
    
    /**
     * 管理员登录
     */
    private void loginAsAdmin(String username, String password) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入管理员账号和密码", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示加载进度条
        binding.progressBar.setVisibility(View.VISIBLE);
        
        // 使用LiveData观察登录结果
        userViewModel.login(username, password).observe(this, user -> {
            binding.progressBar.setVisibility(View.GONE);
            
            if (user != null) {
                // 验证是否是管理员
                if (user.isAdmin() || user.getUserType() == User.TYPE_ADMIN) {
                    // 保存用户信息到SharedPreferences
                    SharedPreferencesUtil.saveUserInfo(this, user.getId(), user.getUsername());
                    
                    // 提示登录成功
                    Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
                    
                    // 启动主界面
                    startMainActivity();
                } else {
                    Toast.makeText(this, "该账号不是管理员账号", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "管理员账号或密码错误", Toast.LENGTH_SHORT).show();
            }
        });
    }
} 